package com.jiedeng.controller;

import com.jiedeng.dao.*;
import com.jiedeng.model.*;
import com.jiedeng.util.ForwardConstants;
import io.swagger.annotations.ApiOperation;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author 覃远龙
 * @ClassName: MessageController
 * @Description:
 * @date 2018/1/29 20:17
 */
@RestController
@RequestMapping("/message")
public class MessageController {
    @Value("${short.message.url}")
    public String shortMessageUrl;
    @Value("${short.message.username}")
    public String username;
    @Value("${short.message.password}")
    public String password;
    @Autowired
    ISysMstTypeRepository sysMstTypeRepository;

    @Autowired
    ISysMessageRepository sysMessageRepository;
    @Autowired
    ITaskRepository taskRepository;
    @Autowired
    IPersonRepository personRepository;

    @Autowired
    ISysMstTypeRepository mstTypeRepository;

    @Autowired
    ISysMsgHandleRepository sysMsgHandleRepository;

    @RequestMapping(value = "/message_type/all", method = RequestMethod.GET)
    @ApiOperation(value = "130102）messagetype表（表字段见数据库设计说明文档6.11消息类型表（sys_msgtype）")
    public List<SysMsgType> findAllType() {
        return mstTypeRepository.findAll();
    }

    //----sys_msg----//
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(value = "013010301）sys_Message表(表字段见数据库设计说明文档6.12消息表（sys_Message）)(数据上行)\n")
    public Rst saveMessage(@RequestBody SysMessage sysMessage) throws Exception {
        if (sysMessage.getMsgTypeId() == 3) {
            //send sms
            //String url = "http://116.213.72.20/SMSHttpService/send.aspx?";
          /*  String url = "http://www.youxinyun.com:3080/Platform_Http_Service/servlet/OldSendSms /send.aspx?";
            String sms_username = "yunchou";
            String sms_password = "325245";*/
            //String sms_password = "yunchou";
            if (sysMessage.getPeopleid() > 0) {
                Person p = personRepository.findById(sysMessage.getPeopleid()).get();
                String sms_mobile = p.getPhone().trim();
                String sms_content = "【JPE系统】系统消息：" + sysMessage.getInfotitle() + "：" + sysMessage.getInfocontent() + "【捷登科技】";
                if (sms_mobile != null && !sms_mobile.isEmpty()) {
                    CloseableHttpClient httpclient = HttpClients.createDefault();
                    HttpGet httpget = new HttpGet(shortMessageUrl + "username=" + username + "&password=" + password + "&mobile=" + sms_mobile + "&content=" + sms_content);
                    CloseableHttpResponse response = null;

                    System.out.println(response);
                    try {
                        response = httpclient.execute(httpget);
                        System.out.println(response.toString());
                    } finally {
                        response.close();
                    }
                }
            }
        }
        Rst rst = new Rst();
        try {
            sysMessageRepository.save(sysMessage);
            SysMsgHandle msgHandle = new SysMsgHandle();
            msgHandle.setMsgId(sysMessage.getId());
            msgHandle.setState(false);
            sysMsgHandleRepository.save(msgHandle);
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            rst.setResultCode(1);
            rst.setMsg("Error");
        }
        return rst;
    }

    public static void main(String[] args) {
        String x = "projectId#2168*taskId#f28b7881-3122-422f-a96e-57f49b21dbc8";
        System.out.println();
    }

    @RequestMapping(value = "/findbyperson", method = RequestMethod.GET)
    public List<SysMessage> findMessageByPerson(Long personId) {
        List<SysMessage> messages = sysMessageRepository.findByPeopleidOrderByTimeDesc(personId);
        List<SysMessage> messageList = new ArrayList<>();
        for (SysMessage sysMessage : messages) {
            if ("任务-打回".equals(sysMessage.getInfotitle())) {
                String param = sysMessage.getParams();
                Task task = taskRepository.getOne(param.split("\\*")[1].split("#")[1]);
                sysMessage.setCloseMemo(task.getCloseMemo());
            }
            List<SysMsgHandle> sysMsgHandles = sysMsgHandleRepository.findByMsgId(sysMessage.getId());
            if (sysMsgHandles != null && sysMsgHandles.size() > 0) {
                sysMessage.setSysMsgHandle(sysMsgHandles.get(0));
                if (!sysMsgHandles.get(0).isState()) {
                    messageList.add(sysMessage);
                }
            } else {
                messageList.add(sysMessage);
            }
        }
        return messages;
    }

    @RequestMapping(value = "/findMessageDetailsById", method = RequestMethod.GET)
    public SysMessage findMessageDetailsById(Long messageId) {
        SysMessage sysMessage = new SysMessage();
        Optional<SysMessage> sysMessageOptional = sysMessageRepository.findById(messageId);
        if (sysMessageOptional.isPresent()) {
            sysMessage = sysMessageOptional.get();
            List<SysMsgHandle> sysMsgHandles = sysMsgHandleRepository.findByMsgId(sysMessage.getId());
            if (sysMsgHandles != null && sysMsgHandles.size() > 0) {
                sysMessage.setSysMsgHandle(sysMsgHandles.get(0));
            }
            Optional<Person> person = personRepository.findById(sysMessage.getSendPeopleId());
            if (person.isPresent()) {
                sysMessage.setSendPeopleName(person.get().getName());
            }
            Optional<SysMsgType> sysMsgType = sysMstTypeRepository.findById(sysMessage.getMsgTypeId());
            if (sysMsgType.isPresent()) {
                sysMessage.setMsgTypeName(sysMsgType.get().getTypeName());
            }
        }
        return sysMessage;
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Rst deleteMsg(Long id) {
        Rst rst = new Rst();
        try {
            Optional optional = sysMessageRepository.findById(id);
            if (optional.isPresent()) {
                sysMessageRepository.deleteById(id);
            }
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    @RequestMapping(value = "/handleMsg/save", method = RequestMethod.POST)
    @ApiOperation(value = "6.13消息处理表（sys_msghandle）)")
    public Rst handleMsg(@RequestBody SysMsgHandle sysMsgHandle) {

        sysMsgHandleRepository.save(sysMsgHandle);

        Rst rst = new Rst();
        rst.setResultCode(0);
        rst.setMsg("OK");

        return rst;
    }

    /**
     * 消息保存
     *
     * @param personId
     * @param opinion
     * @param type
     * @param taskId
     * @param params
     * @return
     */
    @RequestMapping(value = "/saveMsg", method = RequestMethod.POST)
    public void saveMsg(String personId, String opinion, String type, String taskId, String params) {
        Task task = taskRepository.getOne(taskId);
        if (StringUtils.isEmpty(params)) {
            params = "projectId#" + task.getProjectId() + "*taskId#" + taskId;
        }
        String peopleIds = getMsgPeopleId(task, Long.valueOf(personId), type);
        String[] peopleIdsArray = peopleIds.split(",");
        for (String peopleId : peopleIdsArray) {
            SysMessage msg = new SysMessage();
            msg.setSendPeopleId(Long.valueOf(personId));
            msg.setInfotitle(getMsgTitle(type));
            msg.setTime(new Date());
            if (StringUtils.isEmpty(opinion)) {
                msg.setInfoid("");
            } else {
                msg.setInfoid(opinion);
            }
            msg.setInfocontent(task.getCaption());
            msg.setMsgTypeId(3);
            msg.setParams(params);
            msg.setPeopleid(Long.valueOf(peopleId.trim()));
            sysMessageRepository.save(msg);
            SysMsgHandle msgHandle = new SysMsgHandle();
            msgHandle.setMsgId(msg.getId());
            msgHandle.setState(false);
            sysMsgHandleRepository.save(msgHandle);
            try {
                if ("4".equals(type)) {
                    saveMessage(msg);
//                    System.out.println("1111111111111111111111111111111111111");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取消息标题
     *
     * @param type
     * @return
     */
    public String getMsgTitle(String type) {
        if ("1".equals(type)) {
            return ForwardConstants.TASK_PUB;
        }
        if ("2".equals(type)) {
            return ForwardConstants.TASK_REFORM;
        }
        if ("3".equals(type)) {
            return ForwardConstants.TASK_REFORMED;
        }
        if ("4".equals(type)) {
            return ForwardConstants.TASK_REJECT;
        }
        return null;
    }

    /**
     * 过去接受人
     *
     * @param task
     * @param personId
     * @param type
     * @return
     */
    public String getMsgPeopleId(Task task, Long personId, String type) {
        if ("1".equals(type)) {
            if (personId != task.getTaskPersonId()) {
                return task.getExcutePersonId() + task.getTaskPersonId();
            } else {
                return task.getExcutePersonId();
            }
        }
        if ("2".equals(type)) {
            return task.getClosePersonId() + "";
        }
        if ("3".equals(type)) {
            return task.getTaskPersonId() + "";
        }
        if ("4".equals(type)) {
            return task.getClosePersonId() + "";
        }
        return null;
    }
}
